import Mock from 'mockjs';
import { API_CODE } from '@/api/constant';

// 获取应用列表
Mock.mock(/\/api\/app\/list/, 'get', (options: any) => {
  const { page = 1, pageSize = 10 } = options.url.match(/page=(\d+)&pageSize=(\d+)/)
    ? {
        page: parseInt(options.url.match(/page=(\d+)/)[1]),
        pageSize: parseInt(options.url.match(/pageSize=(\d+)/)[1])
      }
    : { page: 1, pageSize: 10 };

  const list = [];
  for (let i = 0; i < pageSize; i++) {
    list.push(
      Mock.mock({
        id: '@guid',
        name: '@ctitle(5, 10)',
        description: '@cparagraph(1, 3)',
        'status|1': ['active', 'inactive', 'pending'],
        'type|1': ['web', 'mobile', 'desktop'],
        createTime: '@datetime',
        updateTime: '@datetime',
        'version|1-100.1-10': 1.0
      })
    );
  }

  return {
    code: API_CODE.SUCCESS,
    message: '获取应用列表成功',
    data: {
      list,
      total: 100,
      page,
      pageSize
    }
  };
});

// 获取应用详情
Mock.mock(/\/api\/app\/detail\/\w+/, 'get', (options: any) => {
  const id = options.url.match(/\/api\/app\/detail\/(\w+)/)[1];

  return {
    code: API_CODE.SUCCESS,
    message: '获取应用详情成功',
    data: Mock.mock({
      id,
      name: '@ctitle(5, 10)',
      description: '@cparagraph(1, 3)',
      'status|1': ['active', 'inactive', 'pending'],
      'type|1': ['web', 'mobile', 'desktop'],
      createTime: '@datetime',
      updateTime: '@datetime',
      'version|1-100.1-10': 1.0,
      'config|1-5': {
        'key|+1': ['apiKey', 'secretKey', 'domain', 'endpoint', 'region'],
        value: '@guid'
      },
      owner: {
        id: '@guid',
        name: '@cname'
      }
    })
  };
});

// 创建应用
Mock.mock(/\/api\/app\/create/, 'post', (options: any) => {
  const data = JSON.parse(options.body);

  return {
    code: API_CODE.SUCCESS,
    message: '创建应用成功',
    data: {
      id: Mock.Random.guid(),
      ...data,
      createTime: Mock.Random.datetime(),
      updateTime: Mock.Random.datetime()
    }
  };
});

// 更新应用
Mock.mock(/\/api\/app\/update\/\w+/, 'put', (options: any) => {
  const id = options.url.match(/\/api\/app\/update\/(\w+)/)[1];
  const data = JSON.parse(options.body);

  return {
    code: API_CODE.SUCCESS,
    message: '更新应用成功',
    data: {
      id,
      ...data,
      updateTime: Mock.Random.datetime()
    }
  };
});

// 删除应用
Mock.mock(/\/api\/app\/delete\/\w+/, 'delete', (options: any) => {
  const id = options.url.match(/\/api\/app\/delete\/(\w+)/)[1];

  return {
    code: API_CODE.SUCCESS,
    message: '删除应用成功',
    data: { id }
  };
});
